package cn.jfstu.freenote.mvc.interceptor;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * cookie设置拦截器
 *
 * @author 贾俊峰
 * @version 1.0
 * @date 2016/12/28 13:52
 */
public class CookieSettingInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        String language = null;
        Locale locale = (Locale) request.getSession().getAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME);
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("language".equals(cookie.getName())) {
                    language = cookie.getValue();
                }
            }
        }
        if (language == null) { // 首次访问
            if (locale == null) {
                locale = request.getLocale();
                request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, locale);
            }
            language = locale.toString();
            Cookie cookie = new Cookie("language", language);
            cookie.setMaxAge(Integer.MAX_VALUE);
            response.addCookie(cookie);
        }

        if (locale == null) { // 用户SESSION失效
            request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, new Locale(language));
        }
        return true;
    }
}
